import mpx from '@mpxjs/core'
import apiProxy from '@mpxjs/api-proxy'

mpx.use(apiProxy, {
  userPromise: true
})

const host = 'http://office.strtv.cn:9002/stk/api/v1'

var app = getApp()

// 普通请求
const request = async (options, showLoading = true) => {
  // 简化开发，如果传入字符串则转换成 对象
  if (typeof options === 'string') {
    options = {
      url: options
    }
  }
  // 显示加载中
  if (showLoading) {
    mpx.showLoading({ title: '加载中' })
  }

  // 拼接请求地址
  options.url = host + '/' + options.url
  var header = {
    ...options.header,
    Sessionid: app.globalData.sessionid,
    Uid: app.globalData.oa_userInfo.uid
  }
  options.header = header
  // options.header.sessionid = app.globalData.sessionid
  // options.header.Authorization = app.globalData.oa_userInfo.uid

  // 调用小程序的 request 方法
  let response = await mpx.request(options)

  if (showLoading) {
    // 隐藏加载中
    mpx.hideLoading()
  }

  // 服务器异常后给与提示
  if (response.statusCode === 500) {
    mpx.showModal({
      title: '提示',
      content: '服务器错误，请联系管理员或重试'
    })
  }

  return response
}

// 生成Inventory
const createInventory = async (params = {}) => {
  // 接口请求 inventories
  let inventoryResponse = await request({
    url: 'inventories.php',
    data: params,
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })

  if (inventoryResponse.statusCode === 201) {
    return inventoryResponse
  }
  return false
}

// 获取centers
const getCenters = async (params = {}) => {
  // 接口请求 centers
  let centerResponse = await request({
    url: 'centers.php',
    data: params,
    method: 'GET'
  })

  if (centerResponse.statusCode === 200) {
    return centerResponse
  }
  return false
}

// 获取departments
const getDepts = async (params = {}) => {
  // 接口请求 inventories
  let deptResponse = await request({
    url: 'departments.php',
    data: params,
    method: 'GET'
  })

  if (deptResponse.statusCode === 200) {
    return deptResponse
  }
  return false
}

export default {
  request,
  createInventory,
  getCenters,
  getDepts
}
